package com.awcall.iot.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ResponseUtils {

    private static final Logger log = LoggerFactory.getLogger(ResponseUtils.class);

    public static void writeString(String data) {
        HttpServletResponse response = getResponse();
        response.setContentType("text/html; charset=utf-8");
        write(response, data);
    }

    public static void writeJson(Object data) {
        HttpServletResponse response = getResponse();
        response.setContentType("application/json; charset=utf-8");
        write(response, JsonUtils.toJson(data));
    }

    private static void write(HttpServletResponse response, String data) {
        PrintWriter writer;
        try {
            writer = response.getWriter();
            writer.write(data);
            writer.flush();
            log.debug("Response Data: {}", data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static HttpServletResponse getResponse() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return ((ServletRequestAttributes) requestAttributes).getResponse();
    }

}
